package cn.tedu.study.security;

import cn.tedu.study.usermodel.entity.vo.UserVo;
import cn.tedu.study.usermodel.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author:yuziji
 * @create: 2023-06-08 11:47
 * @description:
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired(required = false)
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserVo userVo = userMapper.selectByUsername(username);
        if (userVo == null) {
            return null;//用户名不存在，此时会抛异常
        }
//        登录之后将状态改为1，表示在线状态
        userMapper.updateLoginStatus(userVo.getId());

//        根据数据库中的管理员信息，授权
        String role = userVo.getIsAdmin() == 1 ? "ADMIN" : "USER";
        List<GrantedAuthority> list = AuthorityUtils.createAuthorityList(role);
        CustomUserDetail cud = new CustomUserDetail(username, userVo.getPassword(), userVo.getId(),
                userVo.getNickname(), userVo.getAvatar(), userVo.getGender(),
                userVo.getIsAdmin(), userVo.getIntro(), userVo.getAge(), list);
        return cud;
    }
}
